package com.sfac.springboot.modules.account.service.impl;

import java.time.LocalDateTime;
import java.util.Collections;
import java.util.List;
import java.util.Optional;

import javax.transaction.Transactional;

import com.sfac.springboot.modules.account.dao.RoleDao;
import com.sfac.springboot.modules.account.dao.RoleResourceDao;
import com.sfac.springboot.modules.account.dao.UserRoleDao;
import com.sfac.springboot.modules.account.entity.Role;
import com.sfac.springboot.modules.account.service.RoleService;
import com.sfac.springboot.modules.common.vo.Result;
import com.sfac.springboot.modules.common.vo.Search;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;

/**
 * @author jzq
 * @date 2022/8/27 11:08
 */
@SuppressWarnings({"all"})
@Service
public class RoleServiceImpl implements RoleService {

    @Autowired
    private RoleDao roleDao;

    @Autowired
    private UserRoleDao userRoleDao;

    @Autowired
    private RoleResourceDao roleResourceDao;

    @Override
    @Transactional
    public Result<Role> insertRole(Role role) {
        role.setCreateDate(LocalDateTime.now());
        roleDao.insertRole(role);
        return new Result<Role>(Result.ResultStatus.SUCCESS.code,
                "Insert success", role);
    }

    @Override
    @Transactional
    public Result<Role> updateRole(Role role) {
        roleDao.updateRole(role);
        return new Result<Role>(Result.ResultStatus.SUCCESS.code,
                "Update success", role);
    }

    @Override
    @Transactional
    public Result<Object> deleteRoelById(int id) {
        roleDao.deleteRoelById(id);
        userRoleDao.deleteUserRoleByRoleId(id);
        roleResourceDao.deleteRoleResourceByRoleId(id);
        return new Result<Object>(Result.ResultStatus.SUCCESS.code, "Delete success");
    }

    @Override
    public Role getRoleById(int id) {
        return roleDao.getRoleById(id);
    }

    @Override
    public List<Role> getRolesByUserId(int userId) {
        return Optional
                .ofNullable(roleDao.getRolesByUserId(userId))
                .orElse(Collections.emptyList());
    }

    @Override
    public List<Role> getRoles() {
        return Optional.ofNullable(roleDao.getRoles()).orElse(Collections.emptyList());
    }

    @Override
    public PageInfo<Role> getRolesBySearchBean(Search search) {
        search.init();
        PageHelper.startPage(search.getCurrentPage(), search.getPageSize());
        return new PageInfo<Role>(Optional
                .ofNullable(roleDao.getRolesBySearchBean(search))
                .orElse(Collections.emptyList()));
    }

}

